package com.bw.mvvm_comom.network.inteceptor;

import com.blankj.utilcode.util.LogUtils;
import com.bw.mvvm_comom.utils.SignUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Iterator;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;

public class SignInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request oldrequest = chain.request();
        Request.Builder builder = new Request.Builder()
                .url(oldrequest.url())
                .headers(oldrequest.headers());
        RequestBody body = oldrequest.body();
        if (body == null){
            return chain.proceed(oldrequest);
        }
        Buffer buf = new Buffer();
        body.writeTo(buf);
        byte[] buff = new byte[1024];
        String json = "";
        while (buf.read(buff)!=-1){
            json += new String(buff);
        }
        buf.flush();
        buf.close();

        String value = "";
        String result = null;

        try {
            JSONObject job = new JSONObject(json);
            Iterator<String> it = job.keys();
            while (it.hasNext()){
                value += job.getString(it.next());
//                LogUtils.i(value);
            }
            String sign = SignUtils.createSign(value);
            job.put("sign",sign);
            result = job.toString();
            LogUtils.e(result);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"),result);
        builder.post(requestBody);
        return chain.proceed(builder.build());
    }
}
